package com.cn.wanxi.util;

import java.sql.*;

/**
 * 建立数据库连接
 */
public class JDBC {
    /**
     * 1.加载jar包 ，得到数据库驱动  通过反射 ---通过一段字符串得到某个对象
     * 2.建立连接 DriverManager--目的：就是为了得到连接
     * 3.编译sql语句
     * 4.执行sql语句
     * 5.返回结果
     * 6.关闭连接
     */

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取连接
     *
     * @return
     */
    private static Connection getConnection() {
        String url = "jdbc:mysql://121.199.55.96:3306/canyin04?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false";//连接mysql的地址
        String user = "canyin04";//数据库登录用户名
        String password = "123456";//数据库登录密码
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static ResultSet query(String sql) {
        Connection connection = getConnection();
//        PreparedStatement
//        Statement
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            return preparedStatement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static int update(String sql) {
        Connection connection = getConnection();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
